package com.sitech.ibnms.util;

import java.util.List;

import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;

/**
 *
 * @author liujhc
 */
public class JSONUtil {

    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 将java对象转换成json字符串
     *
     * @param obj
     * @return
     */
    public static String toJSON(Object obj) {
        try {
            if (obj == null) {
                return null;
            } else {
                String str = org.apache.struts2.json.JSONUtil.serialize(obj);
            	//return net.sf.json.JSONObject.fromObject(obj).toString();
                return str;
            }
        } catch (Exception ex) {
            throw new RuntimeException("转换Json异常!", ex);
        }
    }

    /**
     * 将json字符串数组转换成java的List对象，对象转换成java的Map对象
     *
     * @param json
     * @return
     */
    public static Object fromJSON(String json) {
        return fromJSON(json, Object.class);
    }

    /**
     * 将json字符串数组转换成指定类型的对象
     *
     * @param json
     * @param type
     * @return
     */
    public static <T> T fromJSON(String json, Class<T> type) {
        try {
            if (json == null) {
                return null;
            } else {
                return mapper.readValue(json, type);
            }
        } catch (Exception ex) {
            throw new RuntimeException("解析Json异常!", ex);
        }
    }

    /**
     * 将json字符串数组转换成指定类型的对象,支持泛型</br>
     *
     * <p>Map&lt;String,User&gt; result = JSONUtil.fromJSON(jsonStr, new
     * TypeReference&lt;Map&lt;String,User&gt;&gt;(){ });</p>
     *
     * @param json
     * @param typeReference
     * @return
     */
    public static <T> T fromJSON(String json, JSONUtil.TypeReference<T> typeReference) {
        try {
            if (json == null) {
                return null;
            } else {
                return (T) mapper.readValue(json, typeReference);
            }
        } catch (Exception ex) {
            throw new RuntimeException("解析Json异常!", ex);
        }
    }

    public abstract static class TypeReference<T extends Object> extends org.codehaus.jackson.type.TypeReference {

        public int compareTo(Object o) {
            return 1;
        }
    }
    
    public static void main(String[] avg){
    	String[] str = new String[2];
    	str[0] = "sms";
    	str[1] = "mms";
    	
    	String json = JSONUtil.toJSON(str);
    	System.out.print(json);
    	json = "[\"sms\",\"mms\"]";
    	List list = (List)JSONUtil.fromJSON(json);
    	for(int j=0;j<list.size();j++){
    		System.out.print(list.get(0).toString());
    	}
    }
}
